package cn.cai.pethome.base.controller;

import cn.cai.pethome.base.util.AjaxResult;
import cn.cai.pethome.user.dto.UserDto;
import cn.cai.pethome.user.service.IUserService;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/verifyCode")
public class VerifyCodeController {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 获取图形验证码 返回base64编码的字符串
     * @param imageCodeKey  32位字符串
     * @return
     */
    @GetMapping("/getImageCode/{imageCodeKey}")
    public AjaxResult getImageCode(@PathVariable("imageCodeKey") String imageCodeKey){
          //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);

        //获取验证码，存储在redis中  imageCodeKey =》63eaf5ac-699c-4bb7-bba4-caaa3fd1b7ca  32位字符串
        String code = captcha.getCode();
        System.out.println("验证码 =》" + code);
        redisTemplate.opsForValue().set(imageCodeKey,code,3, TimeUnit.MINUTES);
        //返回base64位编码字符串
        String imageBase64 = captcha.getImageBase64();
        return AjaxResult.success(imageBase64);

    }

    /**
     * 获取短信验证码
     * @param userDto
     * @return
     */
    @PostMapping("/sendMobileCode")
    public AjaxResult sendMobileCode(@RequestBody UserDto userDto){
        try {
            userService.sendMobileCode(userDto);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }
}
